﻿using UnityEditor;
using UnityEngine;

namespace CWM.Skinn
{
    public static class SkinnGUIHeader
    {
        private static MonoScript @object;

        public static void GUIHeader(GUIContent content, MonoScript @object = null)
        {
            EditorGUILayout.Space();
            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            GUILayout.Label(content, EditorStyles.toolbarButton);
            GUILayout.FlexibleSpace();
            if (GUILayout.Button(SkinnEditorEx.BuiltInAssets.HelpImage, EditorStyles.toolbarButton)) ShowContextHelp();
            EditorGUILayout.Space();
            if (GUILayout.Button(SkinnEditorEx.BuiltInAssets.PopupImage, EditorStyles.toolbarButton)) ShowContextMenuMain(@object);
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space(); EditorGUILayout.Space();
        }

        private static void ShowContextMenuMain(MonoScript @object)
        {
            SkinnGUIHeader.@object = @object;

            var menu = new GenericMenu();
            var nameID = "";
            nameID = "Open";
            menu.AddItem(new GUIContent(nameID), false, ContextMenuHandler, nameID);
            menu.ShowAsContext();
        }

        private static void ContextMenuHandler(object obj)
        {
            var item = obj as string;
            if (item == "Open" && @object) { AssetDatabase.OpenAsset(@object); }
            if (item == SkinnEx.AssetURLS.Itch) Application.OpenURL(SkinnEx.AssetURLS.Itch);
            if (item == SkinnEx.AssetURLS.YouTube) Application.OpenURL(SkinnEx.AssetURLS.YouTube);
            if (item == SkinnEx.AssetURLS.UASForum) Application.OpenURL(SkinnEx.AssetURLS.UASForum);
            if (item == SkinnEx.AssetURLS.UAS) Application.OpenURL(SkinnEx.AssetURLS.UAS);
        }

        private static void ShowContextHelp()
        {
            var menu = new GenericMenu();
            var nameID = "";
            var link = "";

            link = SkinnEx.AssetURLS.UASForum;
            nameID = "Unity Forum";
            menu.AddItem(new GUIContent(nameID), false, ContextMenuHandler, link);

            nameID = "YouTube";
            link = SkinnEx.AssetURLS.YouTube;
            menu.AddItem(new GUIContent(nameID), false, ContextMenuHandler, link);

            nameID = "Store/Unity Asset Store";
            link = SkinnEx.AssetURLS.UAS;
            menu.AddItem(new GUIContent(nameID), false, ContextMenuHandler, link);

            nameID = "Store/Itch.io";
            link = SkinnEx.AssetURLS.Itch;
            menu.AddItem(new GUIContent(nameID), false, ContextMenuHandler, link);
            menu.ShowAsContext();
        }
    }
}